<template>
  <div class="language-selector relative">
    <button
      class="locale-toggle-btn text-gray-700 dark:text-gray-200 flex items-center"
      @click="toggleLanguageDropdown"
    >
      <span class="mr-1">{{ languages.find(lang => lang.code === appStore.locale)?.name || '中文' }}</span>
      <span class="dropdown-arrow">▼</span>
    </button>
    
    <!-- 语言下拉菜单 -->
    <div
      v-if="showLanguageDropdown"
      class="language-dropdown absolute right-0 mt-2 w-32 bg-white dark:bg-gray-700 rounded shadow-lg z-20"
    >
      <div
        v-for="lang in languages"
        :key="lang.code"
        class="dropdown-item px-4 py-2 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-600 text-gray-800 dark:text-white"
        @click="changeLocale(lang.code)"
      >
        {{ lang.name }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAppStore } from '../../store/app'
import { supportedLocales } from '../../i18n'

const { t, locale } = useI18n()
const appStore = useAppStore()

// 语言下拉菜单状态
const showLanguageDropdown = ref(false)

// 使用从i18n导入的支持语言列表
const languages = supportedLocales

// 切换语言
const changeLocale = (langCode: string) => {
  // 使用类型断言确保类型兼容
  const validLocale = langCode as 'zh' | 'en'
  appStore.setLocale(validLocale)
  locale.value = validLocale // 直接更新i18n的locale值，使语言切换立即生效
  showLanguageDropdown.value = false // 关闭下拉菜单
}

// 切换下拉菜单显示状态
const toggleLanguageDropdown = () => {
  showLanguageDropdown.value = !showLanguageDropdown.value
}

// 点击外部关闭下拉菜单
const closeDropdown = (event: MouseEvent) => {
  const target = event.target as HTMLElement
  if (!target.closest('.language-selector')) {
    showLanguageDropdown.value = false
  }
}

// 添加点击事件监听器
window.addEventListener('click', closeDropdown)

// 组件卸载时移除事件监听器
onUnmounted(() => {
  window.removeEventListener('click', closeDropdown)
})
</script>

<style scoped>
.i-back {
  display: inline-block;
  margin-right: 2px;
}

.language-selector {
  position: relative;
}

.dropdown-arrow {
  font-size: 0.7rem;
  margin-left: 2px;
}

.language-dropdown {
  min-width: 120px;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.dropdown-item {
  transition: background-color 0.2s;
}

.dropdown-item:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.dark .dropdown-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}
</style>